
# Load packages
  library(tidyverse)
  library(broom)
  library(scales)
  library(car)
  library(lmtest)
  library(sandwich)
  library(stargazer)
  
# Calculate robust confidence intervals
  se_robust <- function(x)
    coeftest(x, vcov = vcovHC(x, type = "HC0"))[, "Std. Error"]
  p_robust <- function(x)
    coeftest(x, vcov = vcovHC(x, type = "HC0"))[, "Pr(>|t|)"]
  
  #### AUTNES PRE- and POST PANEL Study 2013

# Load data
  load("ObsStudy_00_data_Austria_AUTNES_pre_post_panel_2013.RData")
  data <- table
  
  # Select wave 1
  dt <- data[data$prepost == 1, ]
  
  # Party rating
  colnames(dt)[seq(139, 144, 1)] <- c("rat_SPO", "rat_OVP", "rat_FPO", "rat_BZO", "rat_GRUENE", "rat_STRONACH")
  
  # Set missings NA
  dt[, 139:144][dt[, 139:144] >= 77] <- NA
  
  
  # Coalition evaluations/preferred coalition, there are 2 splits
  # SPLIT A
  colnames(dt)[seq(166, 169, 1)] <- c("A_rat_coal_SPO_GRUENE", "A_rat_coal_SPO_OVP", "A_rat_coal_OVP_FPO", "A_rat_coal_SPO_FPO")
  dt[, 166:169][dt[, 166:169] >= 77] <- NA
  
  # SPLIT B
  colnames(dt)[seq(178, 181, 1)] <- c("B_rat_coal_SPO_GRUENE", "B_rat_coal_SPO_OVP", "B_rat_coal_OVP_FPO", "B_rat_coal_SPO_FPO")
  dt[, 178:181][dt[, 178:181] >= 77] <- NA
  
  # Merge both splits in one variable for each coalition option
  dt$rat_coal_SPO_GRUENE <- dt$A_rat_coal_SPO_GRUENE
  dt$rat_coal_SPO_GRUENE <- ifelse(is.na(dt$rat_coal_SPO_GRUENE), dt$B_rat_coal_SPO_GRUENE, dt$rat_coal_SPO_GRUENE)

  dt$rat_coal_SPO_OVP <- dt$A_rat_coal_SPO_OVP
  dt$rat_coal_SPO_OVP <- ifelse(is.na(dt$rat_coal_SPO_OVP), dt$B_rat_coal_SPO_OVP, dt$rat_coal_SPO_OVP)

  dt$rat_coal_OVP_FPO <- dt$A_rat_coal_OVP_FPO
  dt$rat_coal_OVP_FPO <-ifelse(is.na(dt$rat_coal_OVP_FPO), dt$B_rat_coal_OVP_FPO, dt$rat_coal_OVP_FPO)

  dt$rat_coal_SPO_FPO <- dt$A_rat_coal_SPO_FPO
  dt$rat_coal_SPO_FPO <-ifelse(is.na(dt$rat_coal_SPO_FPO), dt$B_rat_coal_SPO_FPO, dt$rat_coal_SPO_FPO)
  
  # Coalition Likelihood, there are 2 splits as well
  # SPLIT A
  colnames(dt)[seq(170, 173, 1)] <- c("A_coallik_SPO_GRUENE", "A_coallik_OVP_SPO", "A_coallik_FPO_OVP", "A_coallik_FPO_SPO")
  dt[, 170:173][dt[, 170:173] >= 77] <- NA
  
  # SPLIT B
  colnames(dt)[seq(182, 185, 1)] <- c("B_coallik_SPO_GRUENE", "B_coallik_OVP_SPO", "B_coallik_FPO_OVP", "B_coallik_FPO_SPO")
  dt[, 182:185][dt[, 182:185] >= 77] <- NA
  
  # Merge both splits in one variable for each coalition option
  dt$coallik_SPO_GRUENE <- dt$A_coallik_SPO_GRUENE
  dt$coallik_SPO_GRUENE <- ifelse(is.na(dt$coallik_SPO_GRUENE), dt$B_coallik_SPO_GRUENE, dt$coallik_SPO_GRUENE)

  dt$coallik_OVP_SPO <- dt$A_coallik_OVP_SPO
  dt$coallik_OVP_SPO <- ifelse(is.na(dt$coallik_OVP_SPO), dt$B_coallik_OVP_SPO, dt$coallik_OVP_SPO)

  dt$coallik_FPO_OVP <- dt$A_coallik_FPO_OVP
  dt$coallik_FPO_OVP <- ifelse(is.na(dt$coallik_FPO_OVP), dt$B_coallik_FPO_OVP, dt$coallik_FPO_OVP)

  dt$coallik_FPO_SPO <- dt$A_coallik_FPO_SPO
  dt$coallik_FPO_SPO <- ifelse(is.na(dt$coallik_FPO_SPO), dt$B_coallik_FPO_SPO, dt$coallik_FPO_SPO)

  # Reverse-coding of coalition likelihood variable, because low values stand for "very likely/likely" in the original questionnaire 
  
  dt$coallik_SPO_GRUENE = recode(dt$coallik_SPO_GRUENE, "1=4; 2=3; 3=2; 4=1")
  dt$coallik_OVP_SPO = recode(dt$coallik_OVP_SPO, "1=4; 2=3; 3=2; 4=1")
  dt$coallik_FPO_OVP = recode(dt$coallik_FPO_OVP, "1=4; 2=3; 3=2; 4=1")
  dt$coallik_FPO_SPO = recode(dt$coallik_FPO_SPO, "1=4; 2=3; 3=2; 4=1")
  
  # Dependent variable: binary vote choice
  # Q50 [WENN Q49=5, 6, 7, 8, 9 ODER 10]: Und welcher Partei werden Sie bei der Nationalratswahl im September voraussichtlich Ihre Stimme geben?
  # Q51 [WENN Q49<5 ODER Q49=88 ODER 99]: Angenommen, Sie w?rden an der Wahl teilnehmen, f?r welche Partei w?rden Sie sich bei der Nationalratswahl im September am ehesten entscheiden?
  
  dt$w1_q50[dt$w1_q50 >= 77] <- NA
  dt$w1_q51[dt$w1_q51 >= 77] <- NA
  
  # Generate party choice variable
  dt$vote <- dt$w1_q50
  dt$vote <- ifelse(is.na(dt$vote), dt$w1_q51, dt$vote)
  
  # Generate party choice columns based on vote variable
  dt$vc_SPO <- ifelse(dt$vote == 1, 1, 0)
  dt$vc_OVP <- ifelse(dt$vote == 2, 1, 0)
  dt$vc_FPO <- ifelse(dt$vote == 3, 1, 0)
  
  # Coalition evaluation
  Z <- dt %>% select(contains("rat_coal")) 
  Z <- Z[,c(9:12)] %>%
    mutate_all(as.numeric) %>%
    mutate_all(funs(scales::rescale(.,to = c(0, 1))))
  
  rat_coal_SPO <- Z %>% select(rat_coal_SPO_GRUENE, rat_coal_SPO_OVP, rat_coal_SPO_FPO) %>% as.matrix()
  rat_coal_OVP <- Z %>% select(rat_coal_SPO_OVP, rat_coal_OVP_FPO) %>% as.matrix()
  rat_coal_FPO <- Z %>% select(rat_coal_OVP_FPO, rat_coal_SPO_FPO) %>% as.matrix()
  rat_coal_GRUENE <- Z %>% select(rat_coal_SPO_GRUENE) %>% as.matrix()

  # Coalition Likelihood
  gamma <- dt %>% select(contains("coallik_")) 
  gamma <- gamma[,c(9:12)]
  
  coal_lik_SPO <- gamma %>% select(coallik_SPO_GRUENE, coallik_OVP_SPO, coallik_FPO_SPO) %>%
    mutate(sum_exp = exp(coallik_SPO_GRUENE) + exp(coallik_OVP_SPO) + exp(coallik_FPO_SPO),
           coallik_SPO_GRUENE = exp(coallik_SPO_GRUENE)/sum_exp,
           coallik_OVP_SPO = exp(coallik_OVP_SPO)/sum_exp,
           coallik_FPO_SPO = exp(coallik_FPO_SPO)/sum_exp) %>%
    select(-sum_exp) %>%
    as.matrix()
  
  coal_lik_OVP <- gamma %>% select(coallik_OVP_SPO, coallik_FPO_OVP) %>%
    mutate(sum_exp = exp(coallik_OVP_SPO) + exp(coallik_FPO_OVP),
           coallik_OVP_SPO = exp(coallik_OVP_SPO) / sum_exp,
           coallik_FPO_OVP = exp(coallik_FPO_OVP) / sum_exp) %>%
    select(-sum_exp)  %>%
    as.matrix()
  
  
  coal_lik_FPO <- gamma %>% select(coallik_FPO_OVP, coallik_FPO_SPO) %>%
    mutate(sum_exp = exp(coallik_FPO_OVP) + exp(coallik_FPO_SPO),
           coallik_FPO_OVP = exp(coallik_FPO_OVP) / sum_exp,
           coallik_FPO_SPO = exp(coallik_FPO_SPO) / sum_exp) %>%
    select(-sum_exp) %>%
    as.matrix()
  
  coal_lik_GRUENE <- gamma %>% select(coallik_SPO_GRUENE) %>%  # Coalition Likelihood, has to be 1 as only one coalition option available
    mutate(sum_exp = exp(coallik_SPO_GRUENE),
           coallik_SPO_GRUENE = exp(coallik_SPO_GRUENE) / sum_exp) %>%
    select(-sum_exp) %>%
    as.matrix()
  
  
  # Mean-variance model
  EV <- function(gamma,Z){
    gamma %*% Z
  }
  
  Vari <- function(gamma,Z){
    gamma %*% ((Z - as.numeric(EV(gamma,Z)))^2)
  }
  
  N <- nrow(dt)
  
  M_SPO <- sapply(1:N, function(i) EV(coal_lik_SPO[i,], rat_coal_SPO[i,]))
  V_SPO <- sapply(1:N, function(i) Vari(coal_lik_SPO[i,], rat_coal_SPO[i,]))
  
  M_OVP <- sapply(1:N, function(i) EV(coal_lik_OVP[i,], rat_coal_OVP[i,]))
  V_OVP <- sapply(1:N, function(i) Vari(coal_lik_OVP[i,], rat_coal_OVP[i,]))
  
  M_FPO <- sapply(1:N, function(i) EV(coal_lik_FPO[i,], rat_coal_FPO[i,]))
  V_FPO <- sapply(1:N, function(i) Vari(coal_lik_FPO[i,], rat_coal_FPO[i,]))
  
  M_GRUENE <- sapply(1:N, function(i) EV(coal_lik_GRUENE[i,], rat_coal_GRUENE[i,]))
  V_GRUENE <- sapply(1:N, function(i) Vari(coal_lik_GRUENE[i,], rat_coal_GRUENE[i,])) # is 0
  
  # Gender variable, 1 = male, 2 = female
  dt$male <- ifelse(dt$zpsex == 2, 0, dt$zpsex)

  # Education
  # Set missings or observations that do not fit the scheme to NA
  dt$w1_q88 <- ifelse(dt$w1_q88 >= 15, NA, dt$w1_q88)
  
  # PID
  if (!exists("robustnesscheck_pid")) {
    robustnesscheck_pid <- FALSE # PID as robustness?
  }
  dt$w1_q43[dt$w1_q42==2] <- 0
  dt$pid_SPO <- ifelse(dt$w1_q43==1, 1, 0)
  dt$pid_OVP <- ifelse(dt$w1_q43==2, 1, 0)
  dt$pid_FPO <- ifelse(dt$w1_q43==3, 1, 0)
  
  d <- data.frame(
    "vc_SPO" = dt$vc_SPO,
    "vc_OVP" = dt$vc_OVP,
    "vc_FPO" = dt$vc_FPO,
    "rat.SPO" = dt$rat_SPO,
    "rat.OVP" = dt$rat_OVP,
    "rat.FPO" = dt$rat_FPO,
    "rat.GRUENE" = dt$rat_GRUENE,
    "pid_SPO" = dt$pid_SPO,
    "pid_OVP" = dt$pid_OVP,
    "pid_FPO" = dt$pid_FPO,
    "lotterymean.SPO" = M_SPO,
    "lotteryvariance.SPO" = V_SPO,
    "lotterymean.OVP" = M_OVP,
    "lotteryvariance.OVP" = V_OVP,
    "lotterymean.FPO" = M_FPO,
    "lotteryvariance.FPO" = V_FPO,
    "lotterymean.GRUENE" = M_GRUENE,
    "lotteryvariance.GRUENE" = V_GRUENE,
    "sex" = dt$male,
    "age" = dt$zpage,
    "edu" = dt$w1_q88
  )
  
  d$lotteryvariance.SPO <- scales::rescale(d$lotteryvariance.SPO, to = c(0, 1), from = c(0,0.25))
  d$lotteryvariance.OVP <- scales::rescale(d$lotteryvariance.OVP, to = c(0, 1), from = c(0,0.25))
  d$lotteryvariance.FPO <- scales::rescale(d$lotteryvariance.FPO, to = c(0, 1), from = c(0,0.25))
  d$lotteryvariance.GRUENE <- scales::rescale(d$lotteryvariance.GRUENE, to = c(0, 1), from = c(0,0.25))
  
# Save model results
  summary(m1 <- lm(as.formula(paste("vc_SPO ~ lotteryvariance.SPO + lotterymean.SPO + rat.SPO + sex + as.factor(edu) + age", 
                                    if (robustnesscheck_pid) "+ pid_SPO" else "")), d))
  summary(m2 <- lm(as.formula(paste("vc_OVP ~ lotteryvariance.OVP + lotterymean.OVP + rat.OVP + sex + as.factor(edu) + age", 
                                    if (robustnesscheck_pid) "+ pid_OVP" else "")), d))
  summary(m3 <- lm(as.formula(paste("vc_FPO ~ lotteryvariance.FPO + lotterymean.FPO + rat.FPO + sex + as.factor(edu) + age", 
                                    if (robustnesscheck_pid) "+ pid_FPO" else "")), d))
  
  AUT_2013_AUTNES_Pre_Panel_SPO_Variance_Estimate <- tidy(m1) %>% filter(term=="lotteryvariance.SPO") %>% select("estimate")
  AUT_2013_AUTNES_Pre_Panel_SPO_Variance_SE <- se_robust(m1)["lotteryvariance.SPO"] 
  AUT_2013_AUTNES_Pre_Panel_SPO_Mean_Estimate <- tidy(m1) %>% filter(term=="lotterymean.SPO") %>% select("estimate")
  AUT_2013_AUTNES_Pre_Panel_SPO_Mean_SE <- se_robust(m1)["lotterymean.SPO"] 
  
  AUT_2013_AUTNES_Pre_Panel_OVP_Variance_Estimate <- tidy(m2) %>% filter(term=="lotteryvariance.OVP") %>% select("estimate")
  AUT_2013_AUTNES_Pre_Panel_OVP_Variance_SE <- se_robust(m2)["lotteryvariance.OVP"] 
  AUT_2013_AUTNES_Pre_Panel_OVP_Mean_Estimate <- tidy(m2) %>% filter(term=="lotterymean.OVP") %>% select("estimate")
  AUT_2013_AUTNES_Pre_Panel_OVP_Mean_SE <- se_robust(m2)["lotterymean.OVP"] 
  
  AUT_2013_AUTNES_Pre_Panel_FPO_Variance_Estimate <- tidy(m3) %>% filter(term=="lotteryvariance.FPO") %>% select("estimate")
  AUT_2013_AUTNES_Pre_Panel_FPO_Variance_SE <- se_robust(m3)["lotteryvariance.FPO"] 
  AUT_2013_AUTNES_Pre_Panel_FPO_Mean_Estimate <- tidy(m3) %>% filter(term=="lotterymean.FPO") %>% select("estimate")
  AUT_2013_AUTNES_Pre_Panel_FPO_Mean_SE <- se_robust(m3)["lotterymean.FPO"] 
  
  # Harmonize names of the IVs of interest in the models
  names(m1$coefficients)[names(m1$coefficients) == "lotteryvariance.SPO"] <- "Government Lottery Variance"
  names(m1$coefficients)[names(m1$coefficients) == "lotterymean.SPO"] <- "Government Lottery Mean"
  names(m2$coefficients)[names(m2$coefficients) == "lotteryvariance.OVP"] <- "Government Lottery Variance"
  names(m2$coefficients)[names(m2$coefficients) == "lotterymean.OVP"] <- "Government Lottery Mean"
  names(m3$coefficients)[names(m3$coefficients) == "lotteryvariance.FPO"] <- "Government Lottery Variance"
  names(m3$coefficients)[names(m3$coefficients) == "lotterymean.FPO"] <- "Government Lottery Mean"
  
  
  if(!robustnesscheck_pid){
    stargazer(m1, m2, m3, title="Linear regressions of vote choice on perceived government lottery variance and mean (AUTNES Pre-Panel Study 2013).", 
              align=TRUE, 
              dep.var.labels=c("SPO", "OVP", "FPO"),
              omit.stat=c("LL","ser","f"), 
              type = "text",
              se = lapply(list(m1, m2, m3), se_robust),
              p = lapply(list(m1, m2, m3), p_robust),
              out = "TableSM1.tex" 
    )
  }
  
 
